import * as LoginApi from "@/api/user/login.js"
import * as UserApi from "@/api/user/user.js"
import storage from "@/utils/storage.js"
import {ACCESS_TOKEN,USER_ID,USER_ROLE} from "@/store/mutations_type.js"
import {SERVICE_START,SERVICE_STOP} from "@/core/constant/volunteer.js"

export default {
    namespaced: true, 
	state:{
		userId:null,
		token:"",
		role:0,
		complete:0,
		position:{},
	},
	mutations:{
		SET_USERID(state,value){
			state.userId = value
		},
		SET_TOKEN(state,value){
			state.token = value
		},
		SET_COMPLETE(state,value){
			state.complete = value
		},
		SET_ROLE(state,value){
			state.role = value
		},
		SET_POSITION(state,value){
			state.position = value
		},
		
	},
	actions:{
		login({ commit },data){
			const app = this
			return new Promise((resolve,reject)=>{
				LoginApi.login(data)
				.then(res => {
					// 记录token和userID到全局变量
				    commit("SET_TOKEN",res.token)
					commit("SET_USERID",res.userId)
					commit("SET_ROLE",res.role)
					commit("SET_COMPLETE",res.completionDegree)
					// 记录token和userID到缓存
					storage.set(ACCESS_TOKEN,res.token)
					storage.set(USER_ID,res.userId)
					storage.set(USER_ROLE,res.role)
					// 返回响应结果到view层
					resolve(res)
				})
				.catch(reject)
			})
		},
		attest({ commit },data){
			return new Promise((resolve,reject) =>{
				UserApi.attest(data).then(res => {
					commit("SET_ROLE",data.role)
					storage.set(USER_ROLE,data.role)
					resolve(res)
				})
				.catch(reject)
			} )
			
		},
	}
}